package com.example.callback;

import com.example.mapper.UserMapper;
import com.example.model.pojo.Person;
import com.tofries.wxlogin.callback.WeixinLoginCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.example.constant.EnumConstant.USER_STATE;

/**
 * @author zhexueqi
 */
@Component
@Slf4j
public class MyLoginCallback implements WeixinLoginCallback {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public String onLoginSuccess(String sceneId, String openid) {
        // 根据openid查询或创建用户
        Person person = userMapper.getPersonByWxOpenId(openid);
        if (person == null) {
            // 如果用户不存在，返回引导注册的消息
            return "请先完成用户注册！";
        }

        // 设置用户登录状态
        HttpSession session = request.getSession();
        session.setAttribute(USER_STATE, person.getEmployeeAddress());
        
        // 记录登录成功信息
        log.info("微信用户登录成功 - OpenID: {}, 用户地址: {}", openid, person.getEmployeeAddress());
        
        return "登录成功！欢迎回来，" + person.getName();
    }
}
